package com.example.infrastructure.domain.person.repo.impl;

import com.example.infrastructure.domain.person.aggregate.Person;
import com.example.infrastructure.domain.person.repo.PersonRepo;
import com.example.infrastructure.domain.person.repo.dao.PersonDao;
import com.example.infrastructure.domain.person.repo.po.PersonPo;
import com.example.infrastructure.infrastructure.mapper.person.PersonMapper;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author lxh
 * @date 2020/11/23 上午11:48
 **/
@Repository
public class PersonRepoImpl implements PersonRepo {
    private final PersonMapper personMapper;
    private final PersonDao personDao;

    public PersonRepoImpl(PersonMapper personMapper, PersonDao personDao) {
        this.personMapper = personMapper;
        this.personDao = personDao;
    }

    private Person toDo(PersonPo po) {
        return personMapper.toDo(po);
    }

    private PersonPo toPo(Person person) {
        return personMapper.toPo(person);
    }

    private Example<PersonPo> toExample(Example<Person> example) {
        return Example.of(personMapper.toPo(example.getProbe()), example.getMatcher());
    }

    @Override
    public Optional<Person> findById(String personId) {
        return personDao.findById(personId).map(this::toDo);
    }

    @Override
    public List<Person> findPerson(Example<Person> example) {
        return personDao.findAll(toExample(example)).stream().map(this::toDo).collect(Collectors.toList());
    }

    @Override
    public Person save(Person person) {
        return toDo(personDao.save(toPo(person)));
    }

    @Override
    public void delete(String personId) {
        personDao.deleteById(personId);
    }
}
